import {
  AfterDiagnosisOrAudit,
  DetailResult,
  type EcgComplexTerm,
  type EcgData,
  type EcgXWave,
  PreviewReprot,
  type PrintParam,
  RawEcgParam,
  type Study,
  VerticalLine,
} from '@/pages/types/type';
import { useNavigate, useSearchParams } from 'alita';
import {
  Button,
  Card,
  Checkbox,
  Form,
  Grid,
  Modal,
  Picker,
  Popup,
  Radio,
  Space,
  Stepper,
  Steps,
  Tag,
  TextArea,
  Toast,
} from 'antd-mobile';
import {
  CheckCircleFill,
  CheckOutline,
  CheckShieldOutline,
  ClockCircleFill,
  CloseCircleFill,
  CompassOutline,
  DeleteOutline,
  UnorderedListOutline,
  UpOutline,
} from 'antd-mobile-icons';
import React, {
  Dispatch,
  SetStateAction,
  useEffect,
  useRef,
  useState,
} from 'react';
//import AnalysisOverlay from './AnalysisOverlay';
import { getRequestInit, postRequestInit, urlPrefix } from '@/utils/http';
import { ToastHandler } from 'antd-mobile/es/components/toast';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn'; // 导入本地化语言
import relativeTime from 'dayjs/plugin/relativeTime';
import styles from './index.less';
import { DemoBlock } from '@/components/demos-util';
import { Step } from 'antd-mobile/es/components/steps/step';
import { DATE_TIME_FORMAT, SHORT_DATE_TIME_FORMAT, SHORT_TIME_FORMAT } from '@/constants';
dayjs.extend(relativeTime);
dayjs.locale('zh-cn');

const ReportEditor: React.FC<{
  wave: EcgXWave;
  ecgData: EcgData;
  study: Study;
  ecgParams: RawEcgParam[];
  verticalLines: VerticalLine[];
  printParam: PrintParam;
  setEcgParams: Dispatch<SetStateAction<RawEcgParam[]>>;
  setVerticalLines: Dispatch<SetStateAction<VerticalLine[]>>;
  autoAnalysisResult: string;
  setAutoAnalysisResult: Dispatch<SetStateAction<string>>;
  setActiveKey: Dispatch<SetStateAction<string>>;
  setPreKey: Dispatch<SetStateAction<string>>;
  afterPreviewReport: (result: PreviewReprot) => void;
  handleAfteDiagnosisOrAudit: (data: AfterDiagnosisOrAudit) => void;
}> = ({
  wave,
  ecgData,
  study,
  autoAnalysisResult,
  setEcgParams,
  ecgParams,
  verticalLines,
  setActiveKey,
  setPreKey,
  printParam,
  afterPreviewReport,
  handleAfteDiagnosisOrAudit,
}) => {
    const navigate = useNavigate();

    const [diagnosisItems, setDiagnosisItems] = useState<string>('');
    const [isEditing, setIsEditing] = useState<boolean>(false);
    const [showParameterModal, setShowParameterModal] = useState<boolean>(false);
    const [showDiagnosisModal, setShowDiagnosisModal] = useState<boolean>(false);
    const [selectedCategory, setSelectedCategory] = useState<string>('');
    const [selectedDiagnoses, setSelectedDiagnoses] = useState<string[]>([]);
    const [loadFails, setLoadFails] = useState<string[]>([]);
    const [loadOK, setLoadOK] = useState<string | undefined>(undefined);
    const [loadingTimes, setLoadingTimes] = useState<number>(2);
    const [complexTerm, setComplexTerm] = useState<EcgComplexTerm>({
      ecgCharacteristics: [],
      ecgResult: [],
      ecgWJZ: [],
    });

    const {
      testResultStatus,
      impression,
      criticalLevel,
      criticalDescription,
      currentUserCanDoAudit,
      currentUserCanDoDiagnosis,
    } = study!;

    const cantEdit =
      !(currentUserCanDoAudit || currentUserCanDoDiagnosis) ||
      !autoAnalysisResult;

    const textareaRef = useRef<HTMLTextAreaElement>(null);
    const stepperRef = useRef<any>(null);
    const handler = useRef<ToastHandler>();

    type FieldModal = {
      impression: string;
      criticalLevel?: string;
      criticalDescription?: string[];
      testResultStatus: string | null;
    };
    const [form] = Form.useForm<FieldModal>();
    const uwTestResultStatus = Form.useWatch<string>('testResultStatus', form);
    const uwImpression = Form.useWatch<string>('impression', form);

    const [criticalDescriptionVisable, setCriticalDescriptionVisable] =
      useState<boolean>(false);

    function load() {
      let times = 1;
      fetch(`${urlPrefix}/api/term-handle/diag-dict`, getRequestInit())
        .then(async (rsp: Response) => {
          if (rsp.ok) {
            await rsp
              .json()
              .then(({ data, code, msg }: DetailResult<EcgComplexTerm>) => {
                if (code === 0) {
                  if (data) {
                    setComplexTerm(data);
                  } // end if data
                  setLoadOK(msg);
                } else {
                  setLoadFails([...loadFails, msg]);
                  Toast.show({ icon: 'fail', content: msg });
                }
              })
              .catch((reason) => {
                setLoadFails([...loadFails, reason]);
              });
          }
        })
        .catch((reason: any) => {
          console.error(reason);
          setLoadFails([...loadFails, `加载部门：${reason}`]);
        })
        .finally(() => {
          setLoadingTimes(--times);
        });
    }

    useEffect(load, []);

    const [searchParams, setSearchParams] = useSearchParams();
    useEffect(() => {
      if (searchParams.get('id')) {
        form.resetFields();
      }
    }, [searchParams.get('id')]);

    useEffect(() => {
      form.setFieldsValue({
        impression: study.impression || '',
        criticalLevel: study.criticalLevel?.value || undefined,
        criticalDescription: study.criticalDescription
          ? [study.criticalDescription]
          : undefined,
        testResultStatus: study.testResultStatus?.value,
      });
    }, [study]);




    // 处理诊断字典选择
    const handleDiagnosisSelect = (diagnosis: string) => {
      console.log(diagnosis);
      if (selectedDiagnoses.includes(diagnosis)) {
        setSelectedDiagnoses(
          selectedDiagnoses.filter((item) => item !== diagnosis),
        );
      } else {
        setSelectedDiagnoses([...selectedDiagnoses, diagnosis]);
      }
    };

    // 确认选择诊断
    const handleConfirmDiagnosis = () => {
      if (selectedDiagnoses.length > 0) {
        const currentValue = form.getFieldValue('impression') || '';
        const lines = currentValue.split('\n');
        let nextNumber = 1;

        // 找到最大的编号
        for (const line of lines) {
          const match = line.match(/^(\d+)\./);
          if (match) {
            const num = parseInt(match[1]);
            if (num >= nextNumber) {
              nextNumber = num + 1;
            }
          }
        }

        // 添加选中的诊断项
        const newItems = selectedDiagnoses
          .map((diagnosis, index) => `${nextNumber + index}.${diagnosis}`)
          .join('\n');

        const newContent = currentValue
          ? `${currentValue}\n${newItems}`
          : newItems;
        form.setFieldValue('impression', newContent);
      }

      setShowDiagnosisModal(false);
      setSelectedCategory('');
      setSelectedDiagnoses([]);
    };

    const constructPost = (values: FieldModal) => {
      const { criticalDescription: cd, impression, testResultStatus } = values;
      const {
        zoomLevel,
        speedIndex,
        gainIndex,
        horizontalTranslate,
        verticalTranslate,
        devicePixelRatio,
        dataOffset,
      } = printParam;
      return {
        ...values,
        study: study.id,
        mapSnapshotParams: [
          { type: 'zoomLevel', value: zoomLevel },
          { type: 'speedIndex', value: speedIndex },
          { type: 'gainIndex', value: gainIndex },
          { type: 'horizontalTranslate', value: horizontalTranslate },
          { type: 'verticalTranslate', value: verticalTranslate },
          { type: 'devicePixelRatio', value: devicePixelRatio },
          { type: 'dataOffset', value: dataOffset },
        ],
        verticalLines: verticalLines.map(({ type: { value }, position }) => ({
          type: value,
          position,
        })),
        impression,
        autoAnalysisResult,
        testResultStatus,
        ecgParams: ecgParams.map((p) => ({
          param: p.param.value,
          value: p.value,
        })),
        criticalDescription:
          cd && cd.length >= 1 && cd.every((item) => item !== null)
            ? cd[0]
            : undefined,
      };
    };

    function makeDiagnosisOrAudit(values: FieldModal) {
      // Dialog.alert({
      //   content: <pre>{JSON.stringify(values, null, 2)}</pre>,
      // });
      //return;
      //const testMode = true;
      // const { criticalDescription: cd } = values;
      let response: Promise<Response> = fetch(
        `${urlPrefix}/api/study-handle/${currentUserCanDoDiagnosis ? 'make-diagnosis' : 'audit'
        }`,
        postRequestInit(constructPost(values)),
      );
      handler.current = Toast.show({
        icon: 'loading',
        content: `正在${currentUserCanDoAudit ? '审核' : '保存报告'}`,
        maskClickable: false,
        duration: 0,
      });
      response
        .then((rsp: Response) => {
          console.log(rsp);
          if (rsp.ok) {
            rsp
              .json()
              .then(async (x: DetailResult<AfterDiagnosisOrAudit>) => {
                console.log(x);
                const { data, code, msg } = x;
                console.log('id =', data);
                if (code === 0) {
                  handler.current?.close();
                  handleAfteDiagnosisOrAudit(data!);
                } else {
                  Toast.show({ icon: 'fail', content: msg });
                }
              })
              .catch((reason) => {
                Toast.show({ icon: 'fail', content: `发生错误：${reason}` });
              });
          } else {
            Toast.show({ icon: 'fail', content: `发生错误：${rsp.statusText}，错误代码：${rsp.status}` });
          }
        })
        .catch((reason: any) => {
          console.error(reason);
          Toast.show({ icon: 'fail', content: `发生错误：${reason}` });
        })
        .finally(() => { });
    } // end makeDiagnosisOrAudit

    function previewReport() {
      form.validateFields().then((values: FieldModal) => {
        handler.current = Toast.show({
          icon: 'loading',
          content: `正在生成PDF`,
          maskClickable: false,
          duration: 0,
        });
        let response: Promise<Response> = fetch(
          `${urlPrefix}/api/analysis/preview-report`,
          postRequestInit(constructPost(values)),
        );
        response
          .then((rsp: Response) => {
            console.log(rsp);
            if (rsp.ok) {
              rsp
                .json()
                .then(async (x: DetailResult<PreviewReprot>) => {
                  console.log(x);
                  const { data, code, msg } = x;
                  console.log('id =', data);
                  if (code === 0) {
                    const { fileName, uid } = data!;
                    //navigate(`/study/preview-report?uid=${uid}&fileName=${fileName}`)
                    handler.current?.close();
                    // Toast.show({
                    //   icon: 'success',
                    //   content: fileName,
                    // });
                    afterPreviewReport(data!);
                  } else {
                    Toast.show({ icon: 'fail', content: msg });
                  }
                })
                .catch((reason) => {
                  Toast.show({
                    icon: 'fail',
                    content: `预览报告时发生错误：${reason}`,
                  });
                });
            } else {
              Toast.show({ icon: 'fail', content: `发生错误：${rsp.statusText}，错误代码：${rsp.status}` });
            }
          })
          .catch((reason: any) => {
            console.error(reason);
            Toast.show({
              icon: 'fail',
              content: `预览报告时发生错误：${reason}`,
            });
          })
          .finally(() => { });
      }).catch((errorInfo) => {
        // 表单校验失败时的处理
        Toast.show({
          icon: 'fail',
          content: '请检查表单填写是否完整',
        });
        console.log('表单校验失败:', errorInfo);
      });
    } // end function previewReport

    const extractMatchedLines = (inputString: string | undefined): string | undefined => {
      if (!inputString) {
        return undefined;
      }
      const lines = inputString.split('\r\n');
      const result = [];

      const pattern = /^>>\d{3,5}\s(.+)$/;
      let i = 0;
      for (const line of lines) {
        const match = line.match(pattern);
        if (match) {
          result.push(`${++i}.${match[1]}`);
        }
      }
      return result.join('\r\n');
    }

    const impholder = extractMatchedLines(autoAnalysisResult);
    console.log(`impholder=${impholder}`);
    // const {
    //   zoomLevel,
    //   dataOffset,
    //   devicePixelRatio,
    //   horizontalTranslate,
    //   verticalTranslate,
    //   gainIndex,
    //   speedIndex,
    // } = printParam;

    const { name, age, ageUnit, sex, workingMode, hospital, clinicalDepartment, doctor,
      livingOfImageAcquisition, livingOfDiagnosed, livingOfAudited,
      livingOfDiagnosing, livingOfAuditing } = study;
    const livings = [, livingOfImageAcquisition, livingOfDiagnosed, livingOfAudited];
    //var stepIndex = livings.filter(x => x !== undefined).length;
    return (
      <div className={styles.container}>

        <Steps current={ livings.filter(x => x !== undefined).length}>
          <Step title={'检查'} icon={<CheckCircleFill />} description={<>
            {livingOfImageAcquisition.doctor?.name}
            {dayjs(livingOfImageAcquisition.start).format(
              SHORT_TIME_FORMAT,)}
          </>} />
          <Step title='报告' icon={livingOfDiagnosed ? <CheckCircleFill /> : <ClockCircleFill />} description={<>
            {!livingOfDiagnosed && <>{livingOfDiagnosing && livingOfDiagnosing?.leader?.name}</>}
            {livingOfDiagnosed && <>  {livingOfDiagnosed.leader?.name}
              {dayjs(livingOfDiagnosed.start).format(
                SHORT_TIME_FORMAT,)}</>}
          </>} />
          <Step title='审核' icon={livingOfAudited ? <CheckCircleFill /> : <ClockCircleFill />} description={<>
            {!livingOfAudited && <>{livingOfAuditing && livingOfAuditing?.leader?.name}</>}
            {livingOfAudited && <>  {livingOfAudited.leader?.name}
              {dayjs(livingOfAudited.start).format(
                SHORT_TIME_FORMAT,)}</>}
          </>} />
        </Steps>

        <Card className={styles.card}>
          <div
            className={styles.sectionHeader}
            onClick={() => setShowParameterModal(true)}
            style={{ cursor: 'pointer' }}
          >
            <span className={styles.title}>患者</span>
          </div>
          <div className={styles.patCardContent}>
            <Grid columns={2} gap={8}>
              <Grid.Item>
                <Space>姓名：{name}</Space>
              </Grid.Item>
              <Grid.Item>
                <Space>年龄：{`${age + '' + ageUnit.label}`}</Space>
              </Grid.Item>
            </Grid>
            <Grid columns={2} gap={8}>
              <Grid.Item>
                <Space>性别：{sex.label}</Space>
              </Grid.Item>
              <Grid.Item>
                <Space>来源：{workingMode.label}</Space>
              </Grid.Item>
            </Grid>
            <Grid columns={2} gap={8}>
              <Grid.Item>
                <Space>医院：{hospital.label}</Space>
              </Grid.Item>
              <Grid.Item>
                <Space>科室：{clinicalDepartment.label}</Space>
              </Grid.Item>
            </Grid>



            {/* <Grid columns={2} gap={8}>
              <Grid.Item>
                <Space>检查医生：{doctor?.label}</Space>
              </Grid.Item>
              <Grid.Item>
                <Space>检查医生：{doctor?.label}</Space>
              </Grid.Item>
            </Grid>

            <Grid columns={2} gap={8}>
              <Grid.Item>
                <Space>检查时间{ }</Space>
              </Grid.Item>
              <Grid.Item>
                <Space>检查时间{ }</Space>
              </Grid.Item>
            </Grid> */}

          </div>
        </Card>




        {/* 参数范围 */}
        <Card className={styles.card}>
          <div
            className={styles.sectionHeader}
            onClick={() => setShowParameterModal(true)}
            style={{ cursor: 'pointer' }}
          >
            <span className={styles.title}>参数</span>
            <span className={styles.title}>ℹ️范围</span>
          </div>
          <div className={styles.parametersGroup}>
            {ecgParams.map(
              ({ param, value, status, rangeMax, rangeMin }, index) => (
                <div
                  key={index}
                  className={styles.parameterItem}
                  onClick={() => {
                    console.log(`index=${index}, param=${param.label}`);
                    // 自定义参数修改组件
                    const CustomParameterEditor = () => {
                      const [currentValue, setCurrentValue] = useState(value);
                      const handleConfirm = () => {
                        setEcgParams((pre) =>
                          pre.map((ix) =>
                            ix.param.value === param.value
                              ? { ...ix, value: currentValue }
                              : ix,
                          ),
                        );
                        handler.close();
                      };

                      return (
                        <div style={{ padding: '16px 0', textAlign: 'center' }}>
                          <div
                            style={{
                              display: 'flex',
                              alignItems: 'center',
                              justifyContent: 'center',
                              marginBottom: '12px',
                              gap: '16px',
                            }}
                          >
                            <Stepper
                              style={{
                                width: '150px',
                                '--button-width': '32px',
                                '--input-width': '60px',
                                '--input-font-size': '16px',
                                '--button-font-size': '18px',
                              }}
                              ref={stepperRef}
                              defaultValue={value}
                              step={value % 1 === 0 ? 1 : 0.01}
                              onChange={(val) => {
                                setCurrentValue(val);
                              }}
                            />

                            <div
                              style={{
                                fontSize: '14px',
                                color: '#666',
                                whiteSpace: 'nowrap',
                              }}
                            >
                              {param.unit}
                              {rangeMax && ` [${rangeMin},${rangeMax}]`}
                            </div>
                          </div>

                          <div
                            style={{
                              marginTop: '20px',
                              display: 'flex',
                              gap: '12px',
                              justifyContent: 'center',
                            }}
                          >
                            <Button
                              size="small"
                              style={{
                                backgroundColor: '#f5f5f5',
                                color: '#666',
                                fontSize: '12px',
                                padding: '6px 12px',
                                border: 'none',
                              }}
                              onClick={() => handler.close()}
                            >
                              取消
                            </Button>

                            <Button
                              size="small"
                              color="primary"
                              style={{
                                fontSize: '12px',
                                padding: '6px 12px',
                              }}
                              onClick={handleConfirm}
                            >
                              确定
                            </Button>
                          </div>
                        </div>
                      );
                    };
                    const handler = Modal.show({
                      title: `${param.label}`,
                      content: <CustomParameterEditor />,
                      closeOnMaskClick: true,
                    });
                  }}
                >
                  <span className={styles.paramLabel}>{param.label}</span>
                  <span
                    className={styles.paramValue}
                    style={{
                      backgroundColor: !status
                        ? '#FFFFFF'
                        : value <= rangeMin!
                          ? '#FFFF00'
                          : value > rangeMax!
                            ? '#FF0000'
                            : '#FFFFFF',
                    }}
                  >
                    {value}
                  </span>
                  <span className={styles.paramUnit}>{param.unit}</span>
                  {/* {status && status.value === 'reduced' && '下降'}
                {status && status.value === 'elevated' && '上升'} */}
                </div>
              ),
            )}
          </div>
        </Card>

        {/* 自动分析 */}
        <Card className={styles.card}>
          <div className={styles.sectionHeader}>
            {/* <span className={styles.icon}>⚙️</span> */}
            <span className={styles.title}>分析结果</span>

            <span className={styles.icon}>
              <CompassOutline
                color="var(--adm-color-primary)"
                fontSize={24}
                onClick={() => {
                  setPreKey('report');
                  setActiveKey('analysis');
                }}
              />
            </span>
          </div>
          <div className={styles.analysisContent}>
            <pre className={styles.analysisText}>
              {autoAnalysisResult || '没提供自动分析结果！'}
            </pre>
          </div>
        </Card>

        {/** 打印设置 */}
        {/* {printParam &&  <Card className={styles.card}>
          <div className={styles.analysisContent}>
            <pre className={styles.analysisText}>
              dataOffset={dataOffset}; gainIndex={gainIndex}
              ; speedIndex={speedIndex}
              ;horizontalTranslate ={horizontalTranslate}
              ;verticalTranslate={verticalTranslate}
              ;zoomLevel={zoomLevel}
              ; devicePixelRatio={devicePixelRatio}
            </pre>
          </div>
        </Card>} */}

        <Form
          form={form}
          layout={'vertical'}
          onFinish={makeDiagnosisOrAudit}
          footer={
            <div
              style={{
                width: '100%',
                // left: 0,
                // position: 'fixed',
                // bottom: 40,
                // backgroundColor: '#fff',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                padding: '4px 0',
              }}
            >
              <Space>
                <Button
                  size="small"
                  onClick={previewReport}
                  disabled={cantEdit}
                  type="button"
                  color="default"
                >
                  预览报告
                </Button>
                <Button
                  size="small"
                  disabled={cantEdit}
                  type="submit"
                  color="primary"
                >
                  {cantEdit ? '不能操作' : (currentUserCanDoDiagnosis ? '提交报告' : '审核通过')}
                </Button>
              </Space>
            </div>
          }
        >
          <Form.Item
            name="impression"
            label={
              <div
                style={{
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center',
                  width: '100%',
                }}
              >
                <span>诊断说明</span>
                <div style={{ display: 'flex', gap: '8px' }}>
                  <span
                    onClick={() => setShowDiagnosisModal(true)}
                    style={{
                      cursor: 'pointer',
                      fontSize: '16px',
                      color: '#1890ff',
                    }}
                    title="特征字典"
                  >
                    📋
                  </span>
                  <span
                    onClick={() => {
                      const currentValue = form.getFieldValue('impression') || '';
                      const lines:string[] = currentValue.split('\n');
                     form.setFieldValue('impression',  lines.map( (l,index)=>{
                        const numberMatch = l.match(/^(\d+)\./);
                        if(numberMatch){
                          return l;
                        }
                        return `${index+1}.${l}`;
                      }).join('\n'));
                    }}
                    style={{
                      cursor: 'pointer',
                      fontSize: '16px',
                      color: '#1890ff',
                    }}
                    title="序号化"
                  >
                    <UnorderedListOutline />
                  </span>
                </div>
              </div>
            }
            initialValue={impression || ''}
            rules={[{ required: true, message: '诊断说明' }]}
          >
            <TextArea
              placeholder={impholder || '诊断说明'}
              autoSize={{ minRows: 5, maxRows: 8 }}
              showCount={(length, maxLength) => {
                if (length <= 0) {
                  return <CheckOutline color='var(--adm-color-primary)' onClick={() => {
                    form.setFieldsValue({ impression: impholder })
                  }} />
                } else {
                  return <DeleteOutline color='var(--adm-color-warning)' onClick={() => {
                    form.setFieldsValue({ impression: '' })
                  }} />
                }
                return false;//  `${length}/${maxLength}`
              }}
              maxLength={1000}
            />
          </Form.Item>

          <Form.Item
            name="testResultStatus"
            label="诊断结果"
            required
            initialValue={testResultStatus?.value}
            rules={[{ required: true, message: '诊断结果' }]}
          >
            <Radio.Group>
              <Space direction="horizontal">
                <Radio value="normal">
                  <Tag color={'success'}>正常</Tag>
                </Radio>
                <Radio value="abnormal">
                  <Tag color={'warning'}>异常</Tag>
                </Radio>
                <Radio value="danger">
                  <Tag color={'danger'}>危急</Tag>
                </Radio>
              </Space>
            </Radio.Group>
          </Form.Item>

          {uwTestResultStatus && uwTestResultStatus === 'danger' && (
            <>
              <Form.Item
                noStyle
                shouldUpdate={(prevValues, curValues) =>
                  prevValues.criticalDescription !== curValues.criticalDescription
                }
              >
                {({ getFieldValue, setFieldsValue }) => (
                  <Form.Item
                    name="criticalDescription"
                    label="危急值"
                    trigger="onConfirm"
                    required={true}
                    initialValue={
                      criticalDescription ? [criticalDescription] : []
                    }
                    arrowIcon={
                      getFieldValue('criticalDescription')?.length > 0 ? (
                        <CloseCircleFill
                          style={{
                            color: 'var(--adm-color-light)',
                            fontSize: 14,
                          }}
                          onClick={(e) => {
                            e.stopPropagation();
                            setFieldsValue({ criticalDescription: [] });
                          }}
                        />
                      ) : (
                        true
                      )
                    }
                    onClick={() => {
                      setCriticalDescriptionVisable(true);
                    }}
                  >
                    <Picker
                      visible={criticalDescriptionVisable}
                      columns={[complexTerm.ecgWJZ.map(({ name }) => name)]}
                      onClose={() => setCriticalDescriptionVisable(false)}
                      // value={value}
                      // onConfirm={setValue}
                      onSelect={(val, extend) => {
                        console.log('onSelect', val, extend.items);
                      }}
                    >
                      {(items, { open }) => {
                        console.log(
                          `items ==null || items.every(item => item === null)=${items === null || items.every((item) => item === null)
                          }`,
                        );
                        console.log('items=', items);
                        return (
                          <Space align="center">
                            {items === null ||
                              items.every((item) => item === null)
                              ? '未选择'
                              : items
                                .map((item) => item?.label ?? '未选择')
                                .join(' - ')}
                          </Space>
                        );
                      }}
                    </Picker>

                    {/* <DatePicker
                visible={pickerVisible}
                onClose={() => {
                  setPickerVisible(false)
                }}
              >
                {value =>
                  value ? dayjs(value).format('YYYY-MM-DD') : '请选择日期'
                }
              </DatePicker> */}
                  </Form.Item>
                )}
              </Form.Item>

              <Form.Item
                name="criticalLevel"
                required={true}
                initialValue={criticalLevel?.value}
                //disabled={testResultStatus?.value !== 'danger'}
                label="危急等级"
              >
                <Radio.Group>
                  <Space direction="horizontal">
                    {/* <Radio value="none">
                    <Tag color={'success'}>无</Tag>
                  </Radio> */}
                    <Radio value="low">
                      <Tag color={'warning'}>低危</Tag>
                    </Radio>
                    <Radio value="medium">
                      <Tag color={'#ff6430'}>中危</Tag>
                    </Radio>
                    <Radio value="high">
                      <Tag color={'danger'}>高危</Tag>
                    </Radio>
                  </Space>
                </Radio.Group>
              </Form.Item>
            </>
          )}

          {/* <Form.Item
          name="criticalDescription"
          label={'危急值'}
          disabled={testResultStatus?.value !== 'danger'}
          initialValue={criticalDescription || ''}
          rules={[{ required: true, message: '危急值' }]}
        >
          <TextArea
            placeholder="危急值"
            autoSize={{ minRows: 2, maxRows: 3 }}
            showCount
            maxLength={220}
          />
        </Form.Item> */}
        </Form>

        {/* 底部按钮 */}

        {/* 参数范围弹窗 */}
        <Popup
          visible={showParameterModal}
          onMaskClick={() => setShowParameterModal(false)}
          position="top"
          bodyStyle={{ borderBottomLeftRadius: 16, borderBottomRightRadius: 16 }}
        >
          <div className={styles.modalContent}>
            <div className={styles.modalTitle}>
              {study.ageGroup.name}心电参数范围
            </div>
            <div className={styles.parameterTable}>
              {study.ecgParamAgeCfgs.map(
                ({ id, param, valMax, valMin, sex }, index) => (
                  <div key={index} className={styles.parameterRow}>
                    <div className={styles.parameterLabel}>{param.label}</div>
                    <div className={styles.parameterValue}>
                      <span
                        className={styles.currentValue}
                        style={{
                          color:
                            param.haveRangeAdjust &&
                              !ecgParams.some(
                                (eg) =>
                                  eg.param.value === param.value &&
                                  eg.configId === id,
                              )
                              ? 'gray'
                              : 'blue',
                        }}
                      >
                        [{valMin},{valMax}]{sex && sex.label}
                      </span>
                    </div>
                  </div>
                ),
              )}
            </div>
          </div>
        </Popup>

        {/* 诊断字典弹窗 */}
        <Popup
          visible={showDiagnosisModal}
          onMaskClick={() => setShowDiagnosisModal(false)}
          position="bottom"
          bodyStyle={{
            borderTopLeftRadius: 16,
            borderTopRightRadius: 16,
            height: '70vh',
          }}
        >
          <div className={styles.diagnosisModalContent}>
            <div className={styles.diagnosisModalHeader}>
              <div className={styles.diagnosisModalTitle}>诊断字典</div>
              <div className={styles.diagnosisModalButtons}>
                <Button
                  size="small"
                  fill="outline"
                  onClick={() => setShowDiagnosisModal(false)}
                >
                  关闭
                </Button>
                <Button
                  size="small"
                  color="primary"
                  onClick={handleConfirmDiagnosis}
                  disabled={selectedDiagnoses.length === 0}
                >
                  确定
                </Button>
              </div>
            </div>

            {/* 已选择的诊断列表 */}
            {selectedDiagnoses.length > 0 && (
              <div className={styles.selectedDiagnosesContainer}>
                <div className={styles.selectedDiagnosesTitle}>
                  已选择 ({selectedDiagnoses.length})
                </div>
                <div className={styles.selectedDiagnosesList}>
                  {selectedDiagnoses.map((diagnosis, index) => (
                    <div key={index} className={styles.selectedDiagnosisItem}>
                      <span className={styles.selectedDiagnosisText}>
                        {diagnosis}
                      </span>
                      <span
                        className={styles.removeButton}
                        onClick={() => handleDiagnosisSelect(diagnosis)}
                      >
                        ×
                      </span>
                    </div>
                  ))}
                </div>
              </div>
            )}

            <div className={styles.diagnosisModalBody}>
              <div className={styles.categoryList}>
                {complexTerm.ecgCharacteristics.map((item) => (
                  <div
                    key={item.key}
                    className={`${styles.categoryItem} ${selectedCategory === item.key
                      ? styles.categoryItemActive
                      : ''
                      }`}
                    onClick={() => setSelectedCategory(item.key)}
                  >
                    {item.name}
                  </div>
                ))}
              </div>

              <div className={styles.diagnosisList}>
                {selectedCategory &&
                  complexTerm.ecgCharacteristics
                    .find((item) => item.key === selectedCategory)
                    ?.terms?.map((diagnosis, index) => (
                      <div
                        key={`${selectedCategory}-${index}-${diagnosis}`}
                        className={styles.diagnosisItem}
                      >
                        <Checkbox
                          checked={selectedDiagnoses.includes(diagnosis)}
                          onChange={() => handleDiagnosisSelect(diagnosis)}
                        >
                          {diagnosis}
                        </Checkbox>
                      </div>
                    ))}
              </div>
            </div>
          </div>
        </Popup>
        {/* 诊断字典弹窗 结束  */}

        {/* 分析覆盖页面 */}
        {/* <AnalysisOverlay
        visible={showAnalysisOverlay}
        wave={wave}
        study={study}
        ecgData={ecgData}
        onSave={(x)=>{
          console.log(x);
        }}
        onClose={() => setShowAnalysisOverlay(false)}
      /> */}
      </div>
    );
  };

export default ReportEditor;
